// 全局变量
let currentLibrary = null;
let currentMediaItems = [];

// DOM 元素
const libraryListElement = document.getElementById('library-list');
const mediaContentElement = document.getElementById('media-content');
const mediaListElement = document.getElementById('media-list');
const selectedLibraryNameElement = document.getElementById('selected-library-name');
const backToLibrariesButton = document.getElementById('back-to-libraries');
const mediaDetailModal = document.getElementById('media-detail-modal');
const closeDetailModalButton = document.getElementById('close-detail-modal');
const detailTitleElement = document.getElementById('detail-title');
const detailTitleFullElement = document.getElementById('detail-title-full');
const detailInfoElement = document.getElementById('detail-info');
const detailOverviewElement = document.getElementById('detail-overview');
const detailTypeElement = document.getElementById('detail-type');
const detailLanguageElement = document.getElementById('detail-language');
const detailRuntimeElement = document.getElementById('detail-runtime');
const detailReleaseDateElement = document.getElementById('detail-release-date');
const detailRatingElement = document.getElementById('detail-rating');
const detailLibraryElement = document.getElementById('detail-library');
const detailPosterElement = document.getElementById('detail-poster');

// 初始化
function init() {
    // 加载媒体库列表
    loadMediaLibraries();
    
    // 添加事件监听
    backToLibrariesButton.addEventListener('click', showLibrariesView);
    closeDetailModalButton.addEventListener('click', closeDetailModal);
    mediaDetailModal.addEventListener('click', (e) => {
        if (e.target === mediaDetailModal) {
            closeDetailModal();
        }
    });
}

// 加载媒体库列表
function loadMediaLibraries() {
    // 显示加载状态
    libraryListElement.innerHTML = `
        <div class="col-span-full py-8 text-center text-gray-500">
            <i class="fa fa-refresh fa-spin text-xl mb-2"></i>
            <p>正在加载媒体库...</p>
        </div>
    `;
    
    // 发送API请求获取媒体库列表
    fetch('/api/emby_media/library-list')
        .then(response => {
            // 即使状态码不是200，也尝试解析JSON响应
            return response.json().then(data => {
                if (!response.ok) {
                    // 如果有错误信息，使用它；否则使用状态码
                    throw new Error(data.message || `HTTP错误! 状态码: ${response.status}`);
                }
                return data;
            });
        })
        .then(data => {
            // 安全检查响应数据
            if (!data || typeof data !== 'object') {
                throw new Error('无效的响应数据格式');
            }
            
            if (data.success) {
                // 确保data.data是数组格式
                const libraries = Array.isArray(data.data) ? data.data : [];
                
                if (libraries.length > 0) {
                    renderLibraryList(libraries);
                } else {
                    libraryListElement.innerHTML = `
                        <div class="col-span-full py-8 text-center text-gray-500 empty-state">
                            <i class="fa fa-film"></i>
                            <h3>未找到媒体库</h3>
                            <p>请检查Emby媒体服务器连接配置</p>
                        </div>
                    `;
                }
            } else {
                throw new Error(data.message || '获取媒体库失败');
            }
        })
        .catch(error => {
            console.error('加载媒体库失败:', error);
            // 显示友好的错误信息
            libraryListElement.innerHTML = `
                <div class="col-span-full py-8 text-center text-red-500 empty-state">
                    <i class="fa fa-exclamation-circle"></i>
                    <h3>加载失败</h3>
                    <p>${error.message || '无法连接到Emby媒体服务器，请检查配置和网络连接'}</p>
                </div>
            `;
        });
}

// 渲染媒体库列表
function renderLibraryList(libraries) {
    libraryListElement.innerHTML = '';
    
    libraries.forEach(library => {
        const libraryItem = document.createElement('div');
        libraryItem.className = 'library-item';
        libraryItem.dataset.libraryId = library.id;
        libraryItem.dataset.libraryName = library.name;
        
        // 创建封面图元素
        const posterElement = document.createElement('div');
        posterElement.className = 'library-poster';
        
        // 使用占位图或实际封面图
        const posterUrl = library.cover_image || '/static/images/placeholder.png';
        posterElement.style.backgroundImage = `url(${posterUrl})`;
        posterElement.style.backgroundSize = 'cover';
        posterElement.style.backgroundPosition = 'center';
        
        // 创建信息元素
        const infoElement = document.createElement('div');
        infoElement.className = 'library-info';
        
        const nameElement = document.createElement('div');
        nameElement.className = 'library-name';
        nameElement.textContent = library.name;
        
        const typeElement = document.createElement('div');
        typeElement.className = 'library-stats';
        typeElement.textContent = `${library.type || '未知类型'}`;
        
        // 组装元素
        infoElement.appendChild(nameElement);
        infoElement.appendChild(typeElement);
        libraryItem.appendChild(posterElement);
        libraryItem.appendChild(infoElement);
        
        // 添加点击事件
        libraryItem.addEventListener('click', () => {
            loadLibraryContent(library.id, library.name);
        });
        
        libraryListElement.appendChild(libraryItem);
    });
}

// 加载媒体库内容
function loadLibraryContent(libraryId, libraryName) {
    currentLibrary = { id: libraryId, name: libraryName };
    
    // 显示加载状态
    mediaListElement.innerHTML = `
        <div class="col-span-full py-12 text-center text-gray-500">
            <i class="fa fa-refresh fa-spin text-2xl mb-3"></i>
            <p>正在加载${libraryName}的内容...</p>
        </div>
    `;
    
    // 显示媒体内容区域，隐藏媒体库列表
    libraryListElement.parentElement.classList.add('hidden');
    mediaContentElement.classList.remove('hidden');
    selectedLibraryNameElement.textContent = libraryName;
    
    // 发送API请求获取媒体库内容
    fetch(`/api/emby_media/library-content?library_id=${encodeURIComponent(libraryId)}`)
        .then(response => {
            return response.json().then(data => {
                if (!response.ok) {
                    throw new Error(data.message || `HTTP错误! 状态码: ${response.status}`);
                }
                return data;
            });
        })
        .then(data => {
            if (data.success && Array.isArray(data.data)) {
                currentMediaItems = data.data;
                renderMediaItems(currentMediaItems);
            } else {
                throw new Error('获取媒体库内容失败');
            }
        })
        .catch(error => {
            console.error('加载媒体库内容失败:', error);
            mediaListElement.innerHTML = `
                <div class="col-span-full py-12 text-center text-red-500">
                    <i class="fa fa-exclamation-circle text-2xl mb-3"></i>
                    <p>${error.message || '加载媒体库内容失败，请重试'}</p>
                </div>
            `;
        });
}

// 渲染媒体条目列表
function renderMediaItems(mediaItems) {
    mediaListElement.innerHTML = '';
    
    if (mediaItems.length === 0) {
        mediaListElement.innerHTML = `
            <div class="col-span-full py-12 text-center text-gray-500">
                <i class="fa fa-film text-2xl mb-3"></i>
                <p>此媒体库中没有找到媒体内容</p>
            </div>
        `;
        return;
    }
    
    mediaItems.forEach(item => {
        const mediaItem = document.createElement('div');
        mediaItem.className = 'media-item';
        mediaItem.dataset.mediaId = item.id;
        
        // 创建海报图元素
        const posterElement = document.createElement('div');
        posterElement.className = 'media-poster';
        
        // 使用占位图或实际封面图
        const posterUrl = item.cover_image || '/static/images/placeholder.png';
        posterElement.style.backgroundImage = `url(${posterUrl})`;
        posterElement.style.backgroundSize = 'cover';
        posterElement.style.backgroundPosition = 'center';
        
        // 创建信息元素
        const infoElement = document.createElement('div');
        infoElement.className = 'media-info';
        
        const nameElement = document.createElement('div');
        nameElement.className = 'media-name';
        nameElement.textContent = item.name;
        nameElement.title = item.name; // 为了悬停显示完整名称
        
        // 添加类型标签
        const typeTag = document.createElement('div');
        typeTag.className = 'media-type';
        typeTag.textContent = item.type || '未知';
        
        // 组装元素
        infoElement.appendChild(nameElement);
        infoElement.appendChild(typeTag);
        mediaItem.appendChild(posterElement);
        mediaItem.appendChild(infoElement);
        
        // 添加点击事件
        mediaItem.addEventListener('click', () => {
            if (item.type === 'Folder' && item.sub_resources && item.sub_resources.length > 0) {
                // 如果是文件夹且有子资源，加载子资源
                currentMediaItems = item.sub_resources;
                renderMediaItems(currentMediaItems);
            } else {
                // 否则显示媒体详情
                showMediaDetail(item);
            }
        });
        
        mediaListElement.appendChild(mediaItem);
    });
}

// 显示媒体详情
function showMediaDetail(mediaItem) {
    // 设置详情弹窗的内容
    detailTitleElement.textContent = mediaItem.name;
    detailTitleFullElement.textContent = mediaItem.name;
    
    // 设置海报图
    const posterUrl = mediaItem.cover_image || '/static/images/placeholder.png';
    detailPosterElement.src = posterUrl;
    detailPosterElement.alt = mediaItem.name;
    
    // 设置其他信息
    detailInfoElement.textContent = mediaItem.type || '未知类型';
    
    // 根据EmbyMediaUtils返回的数据结构填充其他信息
    // 注意：由于EmbyMediaUtils目前不返回某些详细信息，我们可能需要根据实际情况调整
    detailOverviewElement.textContent = mediaItem.overview || '暂无简介';
    detailTypeElement.textContent = mediaItem.type || '未知';
    detailLanguageElement.textContent = '未知'; // EmbyMediaUtils不返回语言信息
    detailRuntimeElement.textContent = mediaItem.run_time_ticks ? formatRuntime(mediaItem.run_time_ticks) : '未知';
    detailReleaseDateElement.textContent = '未知'; // EmbyMediaUtils不返回发行日期
    detailRatingElement.textContent = '未知'; // EmbyMediaUtils不返回评分
    detailLibraryElement.textContent = currentLibrary ? currentLibrary.name : '未知';
    
    // 显示弹窗
    mediaDetailModal.classList.remove('hidden');
}

// 关闭媒体详情弹窗
function closeDetailModal() {
    mediaDetailModal.classList.add('hidden');
}

// 显示媒体库视图
function showLibrariesView() {
    mediaContentElement.classList.add('hidden');
    libraryListElement.parentElement.classList.remove('hidden');
    currentLibrary = null;
    currentMediaItems = [];
}

// 格式化运行时间（从Ticks转换为分钟）
function formatRuntime(ticks) {
    try {
        // 1 Tick = 100纳秒 = 0.0000001秒
        const seconds = ticks / 10000000;
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = Math.floor(seconds % 60);
        return `${minutes}分${remainingSeconds}秒`;
    } catch (e) {
        return '未知';
    }
}

// 检查连通性（用于首页状态显示）
function checkEmbyConnectivity() {
    return fetch('/api/emby_media/check-connectivity')
        .then(response => response.json())
        .catch(() => ({ success: false, message: '连接失败' }));
}

// 当DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', init);

// 暴露一些函数给全局作用域，以便其他模块（如首页）可以调用
window.checkEmbyConnectivity = checkEmbyConnectivity;